package com.wyx.Common;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.SocketException;
import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionAdvice  {
//java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'zhangsan' for key 'idx_username'
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String>exceptionhinder(SQLIntegrityConstraintViolationException exception){
        String message = exception.getMessage();
        if (message.contains("Duplicate entry")){
            String[] s = message.split(" ");
            return R.error(s[2]+"用户已存在");
        }else {
            return R.error("未知错误");
        }
    }
    @ExceptionHandler(MyException.class)
    public R<String>exceptionhinder(MyException exception){
        String message = exception.getMessage();
        return R.error(message);
    }
    @ExceptionHandler(SocketException.class)
    public R<String>socketexception(SocketException exception){
        System.out.println(exception.getMessage());
        return R.error("服务器闹脾气，请稍后再试");
    }
    @ExceptionHandler(org.apache.catalina.connector.ClientAbortException.class)
    public R<String>Runningtimeout(org.apache.catalina.connector.ClientAbortException exception){
        String message ="服务器闹脾气，请稍后再试";
        return R.error(message);
    }
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public R<String>FileSizeException(FileSizeLimitExceededException exception){
        String msg="图片太大，上传失败";
        return R.error(msg);
    }
    @ExceptionHandler(NullPointerException.class)
    public void NullPointerEr(ServletResponse servletResponse ) throws IOException {
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
